'use strict';

const db = uniCloud.database()
const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  console.log('获取退款记录云函数被调用，参数:', event)
  
  // 管理员访问
  const isAdminAccess = event.isAdmin || false
  let uid = null
  
  if (!isAdminAccess) {
    // 普通用户需要验证 token
    const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken)
    if (!token) {
      return { code: 401, msg: '未登录' }
    }
    
    const uniId = uniIdCommon.createInstance({ context })
    const tokenRes = await uniId.checkToken(token)
    if (tokenRes.code !== 0) {
      return { code: 401, msg: 'token无效或已过期' }
    }
    uid = tokenRes.uid
  } else {
    console.log('管理员访问，跳过token验证')
    uid = 'admin'
  }

  // 构建筛选条件
  const { status, keyword, page = 1, pageSize = 20, startTime, endTime } = event
  let where = {}
  
  // 管理员可以查看所有记录，普通用户只能查看自己的
  if (!isAdminAccess) {
    where.user_id = uid
  }
  
  if (status) {
    where.status = status
  }

  // 关键词搜索
  if (keyword) {
    where = db.command.or([
      { payment_id: new RegExp(keyword, 'i') },
      { original_payment_id: new RegExp(keyword, 'i') },
      { refund_reason: new RegExp(keyword, 'i') }
    ])
    if (!isAdminAccess) {
      where = db.command.and([
        { user_id: uid },
        where
      ])
    }
  }

  // 时间范围查询
  if (startTime && endTime) {
    where.create_time = db.command.gte(new Date(startTime)).and(db.command.lte(new Date(endTime)))
  }

  try {
    // 4. 查询退款记录
    const countResult = await db.collection('refund_records').where(where).count()
    const total = countResult.total
    
    const skip = (page - 1) * pageSize
    const res = await db.collection('refund_records')
      .where(where)
      .orderBy('create_time', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()

    let records = res.data

    // 增强记录数据 - 获取任务信息
    if (isAdminAccess && records.length > 0) {
      const taskIds = [...new Set(records.map(r => r.task_id).filter(id => id))]
      
      if (taskIds.length > 0) {
        const tasksResult = await db.collection('taskList')
          .where({
            _id: db.command.in(taskIds)
          })
          .field({
            _id: true,
            title: true,
            publisher_id: true,
            publisher_name: true,
            receiver_id: true,
            receiver_name: true
          })
          .get()
        
        const tasksMap = {}
        tasksResult.data.forEach(task => {
          tasksMap[task._id] = task
        })
        
        // 合并任务信息
        records = records.map(record => {
          const task = tasksMap[record.task_id]
          
          // 处理时间字段
          const applyTime = record.apply_time || record.create_time
          const createTime = record.create_time
          const normalizedApplyTime = typeof applyTime === 'number' ? applyTime : (typeof createTime === 'object' && createTime.$date ? new Date(createTime.$date).getTime() : typeof createTime === 'object' ? createTime.getTime() : Date.now())
          
          // 处理审核信息 - 自动补充缺失的审核信息
          let auditorName = record.auditor_name || record.admin_name
          let auditTime = record.audit_time || record.update_time
          let auditRemark = record.audit_remark || record.admin_note
          
          // 如果已批准或已完成但缺少审核信息，补充默认值
          if ((record.status === 'approved' || record.status === 'completed') && !auditorName) {
            auditorName = '管理员'
            auditTime = auditTime || normalizedApplyTime
            auditRemark = auditRemark || '管理员处理纠纷自动批准'
          }
          
          return {
            _id: record._id,
            task_id: record.task_id,
            task_title: record.task_title || (task ? task.title : '未知任务'),
            refund_amount: record.refund_amount || record.amount || 0,
            applicant_name: record.applicant_name || (task && record.user_id === task.publisher_id ? task.publisher_name : task ? task.receiver_name : '未知用户') || '未知用户',
            applicant_role: record.applicant_role || (task && record.user_id === task.publisher_id ? 'publisher' : 'receiver'),
            status: record.status || 'pending',
            reason: record.refund_reason || record.reason || 'other',
            reason_detail: record.reason_detail || record.refund_reason_detail || '',
            apply_time: normalizedApplyTime,
            auditor_name: auditorName || null,
            audit_time: auditTime || null,
            audit_remark: auditRemark || null,
            progress: record.progress || getRefundProgress(record.status)
          }
        })
      } else {
        // 没有任务ID或非管理员访问，直接处理记录
        records = records.map(record => {
          const applyTime = record.apply_time || record.create_time
          const createTime = record.create_time
          const normalizedApplyTime = typeof applyTime === 'number' ? applyTime : (typeof createTime === 'object' && createTime.$date ? new Date(createTime.$date).getTime() : typeof createTime === 'object' ? createTime.getTime() : Date.now())
          
          // 处理审核信息 - 自动补充缺失的审核信息
          let auditorName = record.auditor_name || record.admin_name
          let auditTime = record.audit_time || record.update_time
          let auditRemark = record.audit_remark || record.admin_note
          
          // 如果已批准或已完成但缺少审核信息，补充默认值
          if ((record.status === 'approved' || record.status === 'completed') && !auditorName) {
            auditorName = '管理员'
            auditTime = auditTime || normalizedApplyTime
            auditRemark = auditRemark || '管理员处理纠纷自动批准'
          }
          
          return {
            _id: record._id,
            task_id: record.task_id,
            task_title: record.task_title || '未知任务',
            refund_amount: record.refund_amount || record.amount || 0,
            applicant_name: record.applicant_name || '未知用户',
            applicant_role: record.applicant_role || 'publisher',
            status: record.status || 'pending',
            reason: record.refund_reason || record.reason || 'other',
            reason_detail: record.reason_detail || record.refund_reason_detail || '',
            apply_time: normalizedApplyTime,
            auditor_name: auditorName || null,
            audit_time: auditTime || null,
            audit_remark: auditRemark || null,
            progress: record.progress || getRefundProgress(record.status)
          }
        })
      }
    }

    return {
      code: 200,
      msg: '获取成功',
      data: {
        records: records,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      }
    }
  } catch (error) {
    console.error('查询退款记录失败:', error)
    return {
      code: 500,
      msg: '查询失败',
      data: null
    }
  }
}

// 获取退款进度
function getRefundProgress(status) {
  const progressMap = {
    'pending': 1,      // 申请提交
    'approved': 3,     // 审核通过，处理中
    'completed': 4,    // 退款完成
    'rejected': 1,     // 已拒绝
    'processing': 3    // 处理中
  }
  return progressMap[status] || 1
}
